﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OpenMms.Common.Auth;
using OpenMms.Common.Cathe;
using OpenMms.Common.CodeHelp;
using OpenMms.Domain.BLL.User.Login;
using OpenMms.Domain.Enums;
using OpenMms.Domain.Interface;
using OpenMms.Domain.Models;
using OpenMms.Domain.ReponseModels;
using OpenMms.Domain.RequestModels;
using Microsoft.AspNetCore.Mvc;
using OpenMms.Common.Log;
using Newtonsoft.Json;

namespace OpenMms.MVC.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginController : Controller
    {
        #region 注入
        /// <summary>
        /// 登录服务接口
        /// </summary>
        private ILoginService _service;

        private ICacheContext _cache;

        private string _appKey = "directsellauth";

        public LoginController(ILoginService service, ICacheContext cache)
        {
            this._service = service;
            this._cache = cache;
        }
        #endregion

        #region 首页
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public JsonResult Login(PassportLoginRequest request )
        {
          
            //判断验证码
            if (_cache.Get<string>("yzm") == null || _cache.Get<string>("yzm") != request.checkCode)
            {
                return Json(new LoginResult()
                {
                    Code = 501,
                    Message = "验证码输入错误"
                });
            }
            request.AppKey = _appKey;
            //验证
            var result = _service.Do(request);
            if (result.Code != 200)
            {
                return Json(result);
            }
            Response.Cookies.Append("Token", result.Token);
            return Json(result);
        }
        #endregion

        #region 获取数字验证码
        /// <summary>  
        /// 获取数字验证码  
        /// </summary>  
        /// <returns></returns>  
        public FileContentResult NumberVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode);
            _cache.Set("yzm", code,DateTime.Now.AddMinutes(1));
            byte[] codeImage = VerifyCodeHelper.GetSingleObj().CreateByteByImgVerifyCode(code, 80, 40);
            return File(codeImage, @"image/jpeg");
        }
        #endregion
    }
}